<template>
  <div class="app-container">
    <el-input
      clearable
      v-model="search.enName"
      style="width: 200px; padding-left: 5px; padding-top: 10px"
      size="medium"
      placeholder="请输入学校名称"
    />
    <el-select
    clearable
      v-model="search.state"
      style=" width: 200px;
          padding-left: 10px;
          padding-top: 5px;"
      size="medium"
      placeholder="请选择状态"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-button type="primary" size="medium" v-hasBtn="'school_search'" style="margin-left: 10px" icon="el-icon-search" @click="searchList()">查找</el-button>
    <el-button type="primary" size="medium" v-hasBtn="'school_add'" style="margin-left: 10px" icon="el-icon-plus" @click="open()">添加学校</el-button>

    <el-table
      :data="dataBase"
      :default-sort="{prop: 'date', order: 'descending'}"
      border
      style="margin-top: 10px; margin: 10px; width: 98%;"
      :header-cell-style="{ 'text-align': 'center', 'font-size': '12px' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column label="学校名称" prop="enName" />
      <!-- <el-table-column label="账期用户" prop=" nun" /> -->
      <el-table-column label="手机号" prop="tel" />
      <el-table-column label="省份" prop="province" />
      <el-table-column label="城市" prop="city" />
      <el-table-column label="区县" prop="county" />
      <el-table-column label="地址" prop="addr" />
      <!-- <el-table-column label="账期" prop="state" /> -->
      <!-- <el-table-column label="账期状态" prop="time"> -->
        <!-- <template slot-scope="scope">
          <el-popover>
            <div slot="reference">
              <el-tag size="medium" type="success">{{  }}</el-tag>
            </div>
          </el-popover>
        </template> -->

      </el-table-column>
      <el-table-column label="状态" prop="state">
        <template slot-scope="scope">
          <el-popover>
            <div slot="reference">
              <el-tag size="medium" v-if="scope.row.state === 1" type="success">启用</el-tag>
              <el-tag size="medium" v-else type="success">禁用</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button type="text" size="small" v-hasBtn="'school_edit'" @click="edit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" v-hasBtn="'school_start'" @click="openable(scope.row)" v-if="scope.row.state !== 1">启用</el-button>
          <el-button type="text" v-else size="small" v-hasBtn="'school_stop'" style="color: red;" @click="closeAble(scope.row)" >禁用</el-button>
          <el-button type="text" size="small" v-hasBtn="'school_setting'" @click="openAdmin(scope.row)">设置管理员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form ref="ruleForm" label-position="right" :model="ruleForm" :rules="rules" label-width="100px">

        <el-form-item label="学校名称" prop="enName">
          <el-input v-model="ruleForm.enName" style="width: 350px;" />
        </el-form-item>

        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="ruleForm.contactName" style="width: 350px;" />
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="ruleForm.tel" style="width: 350px;" />
        </el-form-item>
        <!-- <el-form-item label="电话号码">
          <el-input-number v-model="num" controls-position="right" :min="1" :max="10" @change="handleChange" />
        </el-form-item> -->
        <el-form-item label="所属区域" prop="regionName">
          <el-cascader
            v-model="quyu"
            :options="option"
            :props="{ expandTrigger: 'hover' , label: 'regionName', value: 'regionName'}"
            @change="handleChanges"
          />
        </el-form-item>

        <el-form-item label="地址" prop="addr">
          <el-input v-model="ruleForm.addr" style="width: 350px;" />
        </el-form-item>

        <!-- <el-form-item label="园所账期">
          <el-input-number v-model="num" controls-position="right" :min="1" :max="10" @change="handleChange" />
        </el-form-item> -->

        <!-- <el-form-item style="padding-left:40px" label="账期状态">
          <el-radio-group v-model="reverse">
            <el-radio :label="true">禁用</el-radio>
            <el-radio :label="false">正常</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item  label="状态" prop="state">
          <el-radio-group v-model="ruleForm.state">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSchool()">确 定</el-button>
      </span>
    </el-dialog>





    <el-dialog title="设置管理员" :visible.sync="dialogTabl">
        <el-form ref="form" label-position="left" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="登录名" prop="account">
            <el-input v-model="form.account" clearable style="width: 350px;" />
          </el-form-item>
          <el-form-item label="密码" prop="pwd">
            <el-input v-model="form.pwd" clearable style="width: 350px;" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAdmin()">确 定</el-button>
        </span>
    </el-dialog>





    <!-- <el-dialog title="内购人员" :visible.sync="dialogTableVisibleq">

      <el-table
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="date"
          label="日期"
          width="180"
        />
        <el-table-column
          prop="name"
          label="姓名"
          width="180"
        />
        <el-table-column label="操作" width="400px">
          <template slot-scope="scope">
            <el-button type="primary" size="small">保存</el-button>
            <el-button type="primary" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      </el-table-column>

      </el-table-column>

      </el-table-column>
      </el-table> -->
    <!-- </el-dialog> -->
    <el-pagination
      background
      style="margin-top: 10px"
      :page-sizes="[10, 20, 50, 100]"
      :current-page.sync="pagemenu.page.page"
      :page-size="pagemenu.page.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @next-click="handleNextChange"
      @prev-click="handlePrevClick"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
  import rsa from '@/utils/rsa'
export default {
  data() {
    return {
      search: {
        enName: '',
        state: '',
      },
      enable: '启用',
      title: '',
      input: '',
      totalCount: 0,
      totalPages: '',
      pagemenu:{
        page:{
          page: 1,
          pageSize: 10,
        }
      },
      dialogTabl:false,
      dialogTableVisible: false,
      dialogTableVisibleq: false,
      dialogFormVisible: false,
      reverse: true,
      form: {
          account: '',
          pwd: '',
          tid: '',
      },
      ruleForm: {
        id: '',
        enName: '',
        contactName: '',
        tel: '',
        addr: '',
        state: 1,
        city: '',
        county: '',
        province: '',
      },
      rules: {
        enName: [
          { required: true, message: '请输入学校名称'},
        ],
        contactName: [
          { required: true, message: '请输入园所负责人' },
        ],
        tel: [
          { required: true, message: '请输入手机号' },
        ],
        state: [
          { required: true, message: '请输入手机号' },
        ]  },
      num: 1,
      value1: [],
      option: [{}],
      value: '',
      dataBase: [{}],
      options:[{
        label: '启用',
        value: 1
      },
       {
         label: '禁用',
         value: 0
       }],
      quyu: '',

    }
  },

  created() {
    this.getList()
    this.getTree()
  },

  methods: {

    openable(val){
        this.$request({
            url: '/school/enableTenant/' + val.id,
            method: 'get'
        }).then(res => {
            if (res.success){
                this.getList()
            }
        })
    },


    closeAble(val){
      this.$request({
            url: 'school/disableTenant/' + val.id,
            method: 'get'
        }).then(res => {
            if (res.success){
                this.getList()
            }
        })
    },



    searchList(){

          if (this.search.enName === '' && this.search.state === ''){
            this.getList()
          } else {
            let data = {
            relation:{
              conditions:[]
            }
          }

          if (this.search.enName){
              data.relation.conditions.push({
                colName: 'en_name',
                ruleType: 'like',
                value: this.search.enName
              })
          }

          if (this.search.state !== ''){
              data.relation.conditions.push({
                colName: 'state',
                ruleType: 'eq',
                value: this.search.state
              })
          }

          this.$request({
              url: '/school/list',
              method: 'post',
              data: {
                page: {
                  page: 1,
                  pageSize: 10
                },
                order:[{
                    colName: 'en_name',
                    orderType: '',
                }],
                relation: data.relation
              }
          }).then(res => {
            this.dataBase = res.data
                this.totalCount = res.totalCount
                this.totalPages = res.totalPages
          })
          }

},



    // searchList(){
    //   this.$request({
    //       url: '/school/list',
    //       method: 'post',
    //       data: this.pagemenu
    //     }).then(res => {
    //         if (res.success){
    //             if (this.input === '' && this.value === ''){
    //               this.dataBase = res.data
    //               this.totalCount = res.totalCount
    //               this.totalPages = res.totalPages
    //             } else if (this.input !== ''){
    //                 var arr = []
    //                 res.data.forEach(item => {
    //                     if (item.enName === this.input){
    //                         arr.push(item)
    //                     }
    //                 })
    //                 this.dataBase = arr
    //             } else if (this.value !== ''){
    //                 var arr = []
    //                 res.data.forEach(item => {
    //                     if (item.state === this.value){
    //                         arr.push(item)
    //                     }
    //                 })
    //                 this.dataBase = arr
    //             } else {
    //               var arr = []
    //                 res.data.forEach(item => {
    //                     if (item.state === this.value && item.enName === this.input){
    //                         arr.push(item)
    //                     }
    //                 })
    //                 this.dataBase = arr
    //             }
               
    //         }
    //     })
    // },




    addSchool(){

      if (this.title === "创建"){
        this.$refs['ruleForm'].validate((valid) => {
            if (valid){
                this.$request({
                    url: '/school/addTenant',
                    method: 'post',
                    data: this.ruleForm
                }).then(res => {
                    if (res.success){
                      this.$notify.success("添加成功")
                      this.getList()
                    } else {
                      this.$notify.warning(res.errMessage)
                    }
                })
            }
      })
      } else {
        this.$refs['ruleForm'].validate((valid) => {
            if (valid){
                this.$request({
                    url: '/school/update',
                    method: 'post',
                    data: this.ruleForm
                }).then(res => {
                    if (res.success){
                      this.$notify.success("更新成功")
                      this.getList()
                    } else {
                      this.$notify.warning(res.errMessage)
                    }
                })
            }
      })
      }

     
      this.dialogTableVisible = false
    },


    edit(val){
        console.log(val)
        this.ruleForm.id = val.id
        this.title = '编辑'
        this.ruleForm.enName = val.enName
        this.ruleForm.tel = val.tel
        this.ruleForm.province = val.province
        this.ruleForm.city = val.city
        this.ruleForm.county = val.county
        this.ruleForm.addr = val.addr
        this.ruleForm.state = val.state
        this.ruleForm.contactName = val.contactName
        this.quyu = [val.province, val.city, val.county]
        this.dialogTableVisible = true
    },











    getCity(value){
        console.log(value)
    },


    getTree(){
        this.$request({
            url: '/region/trees',
            method: 'get',
        }).then(res => {
            if (res.success){
                this.option = this.getTreeData(res.data) 
            }
        })
    },


    getTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				if (data[i].children.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i].children = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i].children);
				}
			}
			return data;
		},


    handleCurrentChange(val) {
      this.pagemenu.page.page = val
      this.getList()
    },

    handlePrevClick(val) {
      this.pagemenu.page.page = val
      this.getList()
    },

    handleNextChange(val) {
      this.pagemenu.page.page = val
      this.getList()
    },

    handleSizeChange(val) {
      this.pagemenu.page.pagesize = val
      this.getList()
    },


    open(){
      this.id = '',
      this.title = '创建'
      this.ruleForm.enName = ''
      this.ruleForm.contactName = '',
      this.ruleForm.tel = '',
      this.ruleForm.addr = '',
      this.ruleForm.state = '',
      this.ruleForm.city = '',
      this.ruleForm.county = '',
      this.ruleForm.province = '',
      this.quyu = ''
      this.dialogTableVisible = true
    },


    addAdmin(){
        this.form.pwd = rsa.rsaPublicData(this.form.pwd)
        this.$request({
          url: '/school/createAdmin',
          method: 'post',
          data: this.form
        }).then(res => {
            if (res.success){
                this.$notify.success("添加成功")
            } 
            else {
              this.$notify.warning(res.errMessage)
            }
        })
        this.dialogTabl = false
    },

    openAdmin(val){
      this.form.tid = val.tid

      this.$request({
          url :'/school/getTenantAdmin/' + val.tid,
          method: 'get'
      }).then(res => {
          if (res.success){
            this.form.account = res.data.account,
            this.form.pwd = res.data.pwd
          } else {
            this.form.account = '',
            this.form.pwd = ''
          }
      })

    
      this.dialogTabl = true
    },


    getList(){
        this.$request({
          url: '/school/list',
          method: 'post',
          data: this.pagemenu
        }).then(res => {
            if (res.success){
                this.dataBase = res.data
                this.totalCount = res.totalCount
                this.totalPages = res.totalPages
            }
        })
    },

    handleChange(value) {
      console.log(value)
    },

    handleChanges(value) {
      console.log(value)
      this.ruleForm.province = value[0],
      this.ruleForm.city = value[1],
      this.ruleForm.county = value[2]
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
